var currentData;

function queryParams(params) {
	$('#theform').serializeArray().forEach(function fn(v){
		params[v.name] = v.value;
	});
    return params;
}

function responseHandler(root) {
	$('#theader').html('表格 记录数:'+root.hits.total+', 搜索耗时:'+root.took+'ms, 分片:'+root._shards.successful +'/'+ root._shards.total);
	$('#desc').html(root.desc);
	
	var groupby = $("input[name='groupby']:checked").val();
	if(groupby == 'TimeHour' || groupby == 'TimeDay' || groupby == 'TimeWeek' || groupby == 'TimeMonth'){
		currentData = redrawByDayUnit(root);
		var index = $("input[name='GraphiIndex']:checked").val();
		redrawChart(index);
		return currentData;
		
	} else {
		alert('error');
	}
}

function getDateSeq(dtrange, s) {
	if (!dtrange || dtrange.length == 0){
		return {};
	}
	var v = $('#TimeDay').val().split('至');
	var dt1 = v[0].trim();
	var dt2 = v[1].trim();
	var r = {};
	
	if(s == 'd') {
		var end =   moment(dt2).format('YYYYMMDD');
		var current = moment(dt1);
		
		while(true){
			var k = current.format('YYYYMMDD');
			r[ k ] = { 'Time':current.format('YYYY-MM-DD') };
			if (k == end){
				break;
			}
			current = current.add(1, 'days');
		}
		
	} else if (s == 'm') {
		var end =   moment(dt2).format('YYYYMM');
		var current = moment(dt1);
		
		while(true){
			var k = current.format('YYYYMM');
			r[ k ] = { 'Time':current.format('YYYY年 MM月') };
			if (k == end){
				break;
			}
			current = current.add(1, 'months');
		}
		
	}
	return r;
}

function redrawByDayUnit(root){
	var groupby = $("input[name='groupby']:checked").val();
	var aggField = '';
	var xAxis = {};
	
	console.log(root);
	
	if(groupby == 'TimeHour') {
		aggField = 'time_hour';
		xAxis = { 
			0: { Time: "0时"},
			1: { Time: "1时"},
			2: { Time: "2时"},
			3: { Time: "3时"},
			4: { Time: "4时"},
			5: { Time: "5时"},
			6: { Time: "6时"},
			7: { Time: "7时"},
			8: { Time: "8时"},
			9: { Time: "9时"},
			10: { Time: "10时"},
			11: { Time: "11时"},
			12: { Time: "12时"},
			13: { Time: "13时"},
			14: { Time: "14时"},
			15: { Time: "15时"},
			16: { Time: "16时"},
			17: { Time: "17时"},
			18: { Time: "18时"},
			19: { Time: "19时"},
			20: { Time: "20时"},
			21: { Time: "21时"},
			22: { Time: "22时"},
			23: { Time: "23时"}
		};
		
	} else if (groupby == 'TimeDay') {
		aggField = 'time_day';
		xAxis = getDateSeq( $('#TimeDay').val() ,'d')
		
	} else if (groupby == 'TimeWeek') {
		aggField = 'time_day_of_week';
		xAxis = { 
			1: { Time: "星期一"},
			2: { Time: "星期二"},
			3: { Time: "星期三"},
			4: { Time: "星期四"},
			5: { Time: "星期五"},
			6: { Time: "星期六"},
			7: { Time: "星期日"}
		};
		
	} else if (groupby == 'TimeMonth') {
		aggField = 'time_yearmonth';
		xAxis = getDateSeq( $('#TimeDay').val() ,'m')
		
	} else {
		alert('错误的统计方式:' + groupby);
		return [];
	}
	
	for(var k in xAxis){
		$.extend( xAxis[k], {
			pv: '-',
			uv: '-',
			
			entrance: '-',
			dc: '-',
			bounce: '-',
			bounce_rate: '-',
			stay_per_user: '-',
			
			first_avg_time: '-',
			max_ts_time: '-',
			
			net_ts_avg_time:	'-',
			max_net_ts:			'-',
			
			render_ts_avg_time:	'-',
			max_render_ts:		'-',
			
			eight_ts_count:		'-',
			eigth_rate:			'-'
		});
	}
	
	var r = [];
	if ( Object.keys(xAxis).length < 0){
		
	} else {
		root.aggregations['group_by@' + aggField + '@' + aggField].buckets.forEach(function (v){
			if(!( v.key in xAxis )){
				xAxis[v.key] = { 'Time':v.key };
			}
			
			$.extend( xAxis[v.key], {
				pv:			v['sum@' + aggField + '@pv'].value,
				uv:			v['sum@' + aggField + '@uv'].value,
				
				entrance:	v['sum@' + aggField + '@entrance'].value,
				dc:			v['sum@' + aggField + '@dc'].value,
				bounce:		v['sum@' + aggField + '@bounce'].value,
				bounce_rate:	(v['sum@' + aggField + '@bounce'].value / v['sum@' + aggField + '@pv'].value * 100).toFixed(2),
				stay_per_user:	(v['sum@' + aggField + '@stay_time_sum'].value / v['sum@' + aggField + '@stay_user_sum'].value).toFixed(2),
				
				first_avg_time:	(v['sum@' + aggField + '@net_ts_sum'].value / 1000 / v['sum@' + aggField + '@net_ts_count'].value + v['sum@' + aggField + '@render_ts_sum'].value / 1000 / v['sum@' + aggField + '@render_ts_count'].value).toFixed(2),
				max_ts_time:	(v['max@' + aggField + '@max_ts_time'].value / 1000).toFixed(0),
				
				net_ts_avg_time:	(v['sum@' + aggField + '@net_ts_sum'].value / 1000 / v['sum@' + aggField + '@net_ts_count'].value).toFixed(2),
				max_net_ts:			(v['max@' + aggField + '@max_net_ts'].value / 1000).toFixed(0),
				
				render_ts_avg_time:	(v['sum@' + aggField + '@render_ts_sum'].value / 1000 / v['sum@' + aggField + '@render_ts_count'].value).toFixed(2),
				max_render_ts:		(v['max@' + aggField + '@max_render_ts'].value / 1000).toFixed(0),
				
				eight_ts_count:		v['sum@' + aggField + '@eight_ts_count'].value,
				eigth_rate:			(v['sum@' + aggField + '@eight_ts_count'].value / v['sum@' + aggField + '@render_ts_count'].value * 100).toFixed(2)
			})
		});
		
		for(var k in xAxis){
			r.push(xAxis[k])
		}
	}
	
	v = root.aggregations["group_by@site_id@site_id"].buckets[0];
	var summaryrow = {};
	if (v === undefined){
		summaryrow = {
			pv: '-',
			uv: '-',
			
			entrance: '-',
			dc: '-',
			bounce: '-',
			bounce_rate: '-',
			stay_per_user: '-',
			
			first_avg_time: '-',
			max_ts_time: '-',
			
			net_ts_avg_time:	'-',
			max_net_ts:			'-',
			
			render_ts_avg_time:	'-',
			max_render_ts:		'-',
			
			eight_ts_count:		'-',
			eigth_rate:			'-'
		}
		
	} else {
		aggField = "site_id"
		summaryrow = {
			pv:			v['sum@' + aggField + '@pv'].value,
			uv:			v['sum@' + aggField + '@uv'].value,
			
			entrance:	v['sum@' + aggField + '@entrance'].value,
			dc:			v['sum@' + aggField + '@dc'].value,
			bounce:		v['sum@' + aggField + '@bounce'].value,
			bounce_rate:	(v['sum@' + aggField + '@bounce'].value / v['sum@' + aggField + '@pv'].value * 100).toFixed(2),
			stay_per_user:	(v['sum@' + aggField + '@stay_time_sum'].value / v['sum@' + aggField + '@stay_user_sum'].value).toFixed(2),
			
			first_avg_time:	(v['sum@' + aggField + '@net_ts_sum'].value / 1000 / v['sum@' + aggField + '@net_ts_count'].value + v['sum@' + aggField + '@render_ts_sum'].value / 1000 / v['sum@' + aggField + '@render_ts_count'].value).toFixed(2),
			max_ts_time:	(v['max@' + aggField + '@max_ts_time'].value / 1000).toFixed(0),
			
			net_ts_avg_time:	(v['sum@' + aggField + '@net_ts_sum'].value / 1000 / v['sum@' + aggField + '@net_ts_count'].value).toFixed(2),
			max_net_ts:			(v['max@' + aggField + '@max_net_ts'].value / 1000).toFixed(0),
			
			render_ts_avg_time:	(v['sum@' + aggField + '@render_ts_sum'].value / 1000 / v['sum@' + aggField + '@render_ts_count'].value).toFixed(2),
			max_render_ts:		(v['max@' + aggField + '@max_render_ts'].value / 1000).toFixed(0),
			
			eight_ts_count:		v['sum@' + aggField + '@eight_ts_count'].value,
			eigth_rate:			(v['sum@' + aggField + '@eight_ts_count'].value / v['sum@' + aggField + '@render_ts_count'].value * 100).toFixed(2)
		}
	}
	
	$('#summarytable').bootstrapTable('updateRow', { index: 0, row:summaryrow });
	
	return r;
}

function redrawChart(index){
	
	var indexName = "";
	
	if(index == 'uv') {
		indexName = '访客数（UV）';
			
	} else if(index == 'ip') {
		indexName = 'IP';
		color = '#da70d6';
		
	} else if(index == 'vv') {
		indexName = '访问次数（VV）';
		color = '#32cd32';
		
	} else if(index == 'nv') {
		indexName = '新访客数（NV）';
		color = '#6495ed';
		
	} else if(index == 'nvp') {
		indexName = '新客率';
		color = '#ff69b4';
		
	} else if(index == 'bounce_rate') {
		indexName = '跳出率';
		color = '#ba55d3';
		
	} else if(index == 'stay_per_user') {
		indexName = '平均访问时长(秒)';
		color = '#cd5c5c';
		
	} else if(index == 'pv_per_vv') {
		indexName = '平均访问页面数';
		color = '#ffa500';
		
	} else {
		//pv
		index = 'pv';
		indexName = '浏览量（PV）';
		color = '#40e0d0';
	}
	
	var xAxis = [];
	var data = [];
	currentData.forEach(function(v){
		xAxis.push(v['Time']);
		data.push(v[index]);
	});
	
	option = {
	    title: {
	        text: indexName
	    },
	    tooltip : {
	        trigger: 'axis'
	    },
	    grid: {
	        left: '3%',
	        right: '4%',
	        bottom: '3%',
	        containLabel: true
	    },
	    xAxis : [
	        {
	            type : 'category',
	            boundaryGap : false,
	            data : xAxis
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
	    series : [
	        {
	            name: indexName,
	            type:'line',
	            areaStyle: { normal: { } },
	            data: data
	        }
	    ]
	};
	var myChart = echarts.init(document.getElementById('main'));
	myChart.setOption(option, true);
}


function initTable(){
	
	$('#thetable').bootstrapTable('destroy');
	$('#thetable').bootstrapTable({
		showExport: true,
		url: '/analytics/page_history.json',
		method: 'post',
		queryParams: queryParams,
		responseHandler: responseHandler,
		idField: 'Time',
		classes: 'table table-hover table-condensed',
		striped: true,
		dataShowExport: true,
		sortStable: true,
		pagination: false,
		columns: [
			{
		        field: 'Time',
		        sortable: true,
		        title: '时间'
		    }, {
		        field: 'pv',
		        title: '浏览量（PV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'uv',
		        title: '访客数（UV）',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'entrance',
		        title: '入口页次数',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'dc',
		        title: '贡献下游浏览量',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'bounce',
		        title: '退出页次数',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'bounce_rate',
		        title: '退出率',
		        sortable: true,
		        formatter: nump
		    }, {
		        field: 'stay_per_user',
		        title: '平均停留时长(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'first_avg_time',
		        title: '平均首屏时间(秒)',
		        formatter: numt
		    }, {
		        field: 'max_ts_time',
		        title: '最大首屏时间(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'net_ts_avg_time',
		        title: '平均网络连接时长(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'max_net_ts',
		        title: '最大网络连接时长(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'render_ts_avg_time',
		        title: '平均页面渲染时长(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'max_render_ts',
		        title: '最大页面渲染时长(秒)',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'eight_ts_count',
		        title: '首屏大于8秒请求量',
		        sortable: true,
		        formatter: numt
		    }, {
		        field: 'eigth_rate',
		        title: '首屏大于8秒请求比例',
		        sortable: true,
		        formatter: nump
		    }
		]
	});
	
}

function switchTable(){
	groupby = $("input[name='groupby']:checked").val();
		
	if (groupby == 'TimeHour'){
		initTable();
		
	} else if (groupby == 'TimeDay' || groupby == 'TimeWeek' || groupby == 'TimeMonth'){
		initTable();
		
	} else {
		alert('找不到聚合方法:'+groupby);
	}
}

$(document).ready(function () {
	$("input[name='groupby']").change(function() {
		switchTable();
	});

	$('#theform_commit').click(function (){
		switchTable();
	});
	
	$("#GraphiIndex").change(function() {
		redrawChart($(this).val());
	});
	
	initDateRangePick($('#TimeDay'));
	
	$('#summarytable').bootstrapTable({
		data: [{
			pv: '-',
			uv: '-',
			ip: '-',
			vv: '-',
			nv: '-',
			nvp: '-',
			bounce_rate: '-',
			stay_per_user: '-',
			pv_per_vv: '-'
		}]
	});
	
	$.ajax({
		url: '/analytics/branch.json', 
		type: 'POST', 
		data:{ type:'site' }, 
		dataType: 'json', 
		error: function(){
			alert('Error loading branch');
		}, 
		success: function(root){
			var control = $('#BranchId')
			control.find('option').remove().end();
			control.append('<option value="">全部</option>');
			var kv = {}
			root.aggregations['group_by@branch_id@branch_id'].buckets.forEach(function (v){
				if (v.key.length == 0) return;
				if (b2b_map !== undefined && b2b_map[v.key] !== undefined){
					kv[v.key] = b2b_map[v.key] + " ( pv:" + v['sum@branch_id@pv'].value + " )";
				} else {
		        	kv[v.key] = v.key + " ( pv:" + v['sum@branch_id@pv'].value + " )";
		        }
			});
			$.each(kv, function (k,v){	
				control.append($('<option>', { value : k, text: v }));
			});
			
			initBranch();
			switchTable();
		} 
	});
});
